package controller

import (
	"context"

	tableUtils "gitee.com/klein-x/biz/model/mysql/table/utils"
	redis "gitee.com/klein-x/biz/module/db/redis/captcha"
	"gitee.com/klein-x/biz/module/sms"
	"gitee.com/klein-x/biz/xutils"
	"github.com/cloudwego/hertz/pkg/common/hlog"
)

const captchaLen = 4
const (
	ErrCode_Success        = 0000
	ErrCode_BuildCaptcha   = 1001
	ErrCode_BlackList      = 1002
	ErrCode_SendSms        = 1003
	ErrCode_SaveCaptcha    = 1004
	ErrCode_InvaildResId   = 1005
	ErrCode_InvaildResType = 1006
)

func Captcha(ctx context.Context, phone string) error {
	//1. 检查手机号有没有被放进黑名单
	if err := redis.InCaptchaBlackList(ctx, phone); err != nil {
		return xutils.Error(ErrCode_BlackList, err)
	}

	// 生成验证码
	cap, err := xutils.RandomCaptcha(captchaLen)
	if err != nil {
		return xutils.Error(ErrCode_BuildCaptcha, err)
	}
	hlog.CtxDebugf(ctx, "发送短信验证码%v", cap)
	if err := sms.SendCaptcha(phone, cap); err != nil {
		hlog.CtxErrorf(ctx, "短信发送失败[phone:%s, captch:%s, error:%v]", phone, cap, err)
		return xutils.Error(ErrCode_SendSms, "sms error")
	}
	// 将验证码保存到redis中
	if err := redis.SetCaptcha(ctx, phone, cap); err != nil {
		hlog.CtxErrorf(ctx, "保存验证码失败[phone:%s, captch:%s, error:%v]", phone, cap, err)
		return xutils.Error(ErrCode_SaveCaptcha, "save captcha error")
	}
	return nil
}

func DwloadResource(ctx context.Context, UUID string) (*DwloadRes, error) {
	//1. 可以用redis加速一些常用图片的获取，目前先不做逻辑
	//2. 获取图片信息

	res, err := tableUtils.ResourceGetById(UUID)
	if err != nil {
		return nil, xutils.Error(ErrCode_InvaildResId, err)
	}
	if res == nil {
		return nil, xutils.Error(ErrCode_InvaildResId, "无效的资源ID")
	}

	var dwRes DwloadRes
	switch res.Type {
	case "1":
		dwRes.Type = "image"
	default:
		return nil, xutils.Error(ErrCode_InvaildResType, "无效的资源类型")
	}
	dwRes.Data = res.Data

	return &dwRes, nil
}

func UploadResource(ctx context.Context, resType string, resData string) (string, error) {
	uuid, err := xutils.RandomUUID()
	if err != nil {
		return "", err
	}

	err = tableUtils.ResourceInsertById(uuid, resType, resData)
	if err != nil {
		return "", err
	}
	return uuid, nil
}
